package daos;

import java.util.List;

import hibernateUtils.HibernateUtil;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
//import javax.persistence.Query;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;



import mediasManagement.Exemplary;
import mediasManagement.Media;

import exceptions.BadParametersException;
import exceptions.MediaExistsException;
import exceptions.SubscriberExistsException;


import subscribersManagement.Entitled;

import subscribersManagement.Subscriber;


public class SubscriberDAO {

	public boolean add(Subscriber subscriber) {
		
		Session session= HibernateUtil.openSession();
		try{
			for(Entitled ent: subscriber.getEntitles()){
				session.save(ent);
			}
			
			session.save(subscriber);
		} catch (Exception e) {
			System.err.println("Problem when saving");
			e.printStackTrace();
			return false;
		}
	
		return true;
	}
	
	public List<Subscriber> findAllByName(String subscriberName) {
		Session session = HibernateUtil.openSession();
		Query query=session.createQuery("from Subscriber as s where s.firstName = "+"'"+
		subscriberName+"'"+" or s.lastName= "+"'"+subscriberName+"'");
		List<Subscriber> subscribers= query.list();
		return subscribers;
	}


	
	public boolean contains(Subscriber subscriber) throws MediaExistsException {
		Session session = HibernateUtil.openSession();
		if (subscriber== null) throw new MediaExistsException();
		Subscriber s = (Subscriber) session.get(Subscriber.class,subscriber.getNumber());
		if (s ==null) return false;
		else return s.equals(subscriber);	
	}
	
	public Subscriber GetSingleSubscriberByLastName(String lastName) throws SubscriberExistsException {
		Session session = HibernateUtil.openSession();
	Criteria criteria = session.createCriteria(Subscriber.class).add(Restrictions.eq("lastName", lastName));
	Subscriber subscriber = (Subscriber)criteria.uniqueResult();
		if (subscriber == null) throw new SubscriberExistsException();
		else
			return subscriber;
	}
	
	public Subscriber GetSubscriberById(long number) throws SubscriberExistsException {
		Session session = HibernateUtil.openSession();
	Criteria criteria = session.createCriteria(Subscriber.class).add(Restrictions.eq("number", number));
	Subscriber subscriber = (Subscriber)criteria.uniqueResult();
		if (subscriber == null) throw new SubscriberExistsException();
		else
			return subscriber;
	}
}
